﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel.Composition;
using System.Diagnostics.Contracts;

namespace EBA.IoC
{
    /// <summary>
    /// 注入信息
    /// </summary>
    public class ImportConvention
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="hostingType"></param>
        public ImportConvention(Type hostingType)
        {
        
            this.HostingType = hostingType;

            this.Members = new List<AutowiredMember>();

            var fields = this.HostingType.GetFields();
            foreach (var field in fields)
            {
                TryLoadMebmerImport(field);
            }

            var properties = this.HostingType.GetProperties();

            foreach (var property in properties)
            {
                TryLoadMebmerImport(property);
            }

            TryLoadConstructorInjection();

        }

        /// <summary>
        /// 目标对象类型
        /// </summary>
        public Type HostingType { get; private set; }

        /// <summary>
        /// 构造子注入
        /// </summary>
        public AutowiredConstructor Constructor { get; set; }
        /// <summary>
        /// 属性注入
        /// </summary>
        public List<AutowiredMember> Members { get; set; }


        /// <summary>
        /// 载入属性注入信息
        /// </summary>
        /// <param name="member"></param>
        private void TryLoadMebmerImport(MemberInfo member)
        {
            var import = member.GetCustomAttributes(typeof(ImportAttribute), true).OfType<ImportAttribute>().FirstOrDefault();
            if (import != null)
            {
                this.Members.Add(new AutowiredMember(member, import));
            }
            else
            {
                var importMany = member.GetCustomAttributes(typeof(ImportManyAttribute), true).OfType<ImportManyAttribute>().FirstOrDefault();
                if (importMany != null)
                {
                    this.Members.Add(new AutowiredMember(member, importMany));
                }
            }
        }

        /// <summary>
        /// 载入构造子注入信息
        /// </summary>
        private void TryLoadConstructorInjection()
        {
            var constructors = this.HostingType.GetConstructors();

            foreach (var constructor in constructors)
            {
                var import = constructor.GetCustomAttributes(typeof(ImportingConstructorAttribute), false).OfType<ImportingConstructorAttribute>().FirstOrDefault();
                if (import != null)
                {
                    var injection = new AutowiredConstructor(constructor);
                    this.Constructor = injection;
                    break;//only one constructor injection is available
                }

            }
        }
    }
}
